import { registerLocaleData } from '@angular/common';
import { Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STComponent, STData, STRequestOptions } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFSchemaEnum, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SearchDrawerService, ShipperBaseService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
import { OrderManagementService } from '../../services/order-management.service';
import { BasicTableComponent } from 'src/app/routes/commom/components/basic-table/basic-table.component';

@Component({
  selector: 'app-supply-managemenSt-risk',
  templateUrl: './risk.component.html',
  styleUrls: ['../../../commom/less/commom-table.less', './risk.component.less']
})
export class OrderManagementRiskComponent extends BasicTableComponent implements OnInit {
  uiView: SFUISchema = {};
  schemaView: SFSchema = {};
  auditMany = false;
  loading: boolean = true;
  auditId: any;
  auditIdR: any;
  isVisibleRE = false;
  resourceStatus: any;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  columns: STColumn[] = [];
  tabs = {
    underwayQuantity: 0,
    cancelQuantity: 0,
    receivedQuantity: 0,
    stayQuantity: 0
  };
  constructor(
    public service: OrderManagementService,
    public shipperservice: ShipperBaseService,
    public router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const a: any = {};
    if (this.resourceStatus) {
      a.representationsStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sfValue || {});
    delete params._$expand;
    return {
      ...a,
      ...params,
      createTime: {
        start: this.sfValue?.createTime?.[0] || '',
        end: this.sfValue?.createTime?.[1] || ''
      }
    };
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    const a: any = {};
    if (this.resourceStatus) {
      console.log(this.resourceStatus);
      
      a.representationsStatus = this.resourceStatus;
    }
    const params: any = Object.assign({}, this.sfValue || {});
    delete params._$expand;
    if (this.sfValue) {
      Object.assign(requestOptions.body, {
        ...a,
        ...params,
        createTime: {
          start: this.sfValue?.createTime?.[0] || '',
          end: this.sfValue?.createTime?.[1] || ''
        }
      });
    }
    console.log(requestOptions);
    
    this.loading = true;
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    console.log(data);
    this.loading = false;
    return data.map(item => ({
      ...item,
      disabled: item.representationsStatus !== '2'
    }));
  };
  search() {
    this.st?.load(1);
    this.getGoodsSourceStatistical();
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  ngOnInit(): void {
    this.getGoodsSourceStatistical();
    this.initSF();
    this.initST();
  }
  getGoodsSourceStatistical() {
    this.service.request(this.service.$api_get_listStatisticalStatus, this.reqParams).subscribe(res => {
      if (res) {
        res.forEach((element: any) => {
          console.log(element.representationsStatus);
          if (element.representationsStatus === '1') {
            this.tabs.stayQuantity = element.quantity;
          } else if (element.representationsStatus == '4') {
            this.tabs.cancelQuantity = element.quantity;
          } else if (element.representationsStatus == '3') {
            this.tabs.receivedQuantity = element.quantity;
          } else if (element.representationsStatus == '2') {
            this.tabs.underwayQuantity = element.quantity;
          }
        });
        console.log(this.tabs);
      }
    });
  }
  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入订单号'
          }
        },
        resourceCode: {
          type: 'string',
          title: '货源编号'
        },
        externalResourceCode: {
          type: 'string',
          title: '外部订单号'
        },
        loadingPlace: {
          type: 'string',
          title: '装货地'
        },
        dischargePlace: {
          type: 'string',
          title: '卸货地'
        },
        driverName: {
          title: '承运司机',
          type: 'string'
        },
        carNo: {
          title: '车牌号',
          type: 'string'
        },
        payeeName: {
          type: 'string',
          title: '车队长'
        },
        wayBillType: {
          title: '运单类型',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bill:type' },
            containsAllLabel: true
          } as SFSelectWidgetSchema
        },
        billSource: {
          title: '订单来源',
          type: 'string',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bill:source' },
            containsAllLable: true
          } as SFSelectWidgetSchema
        },
        shipperAppUserName: {
          type: 'string',
          title: '托运人',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service
                  .request(this.service.$api_enterpriceList, { enterpriseName: str })
                  .pipe(map((res: any) => (res as any[]).map(i => ({ label: i.enterpriseName, value: i.enterpriseName } as SFSchemaEnum))))
                  .toPromise();
              } else {
                return of([]);
              }
            }
          } as SFSelectWidgetSchema
        },
        enterpriseInfoId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.shipperservice.getNetworkFreightForwarder()
          }
        },
        createTime: {
          title: '创建时间',
          type: 'string',
          ui: {
            widget: 'date',
            mode: 'range',
            format: 'yyyy-MM-dd',
            allowClear: true
          } as SFDateWidgetSchema
        }
      },
      type: 'object'
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', width: '50px', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      {
        title: '订单号',
        width: '200px',
        className: 'text-left',
        render: 'billCode'
      },
      {
        title: '申诉状态',
        width: '100px',
        className: 'text-center',
        index: 'representationsStatusLabel'
      },
      {
        title: '货源编号',
        width: '200px',
        className: 'text-left',
        index: 'resourceCode'
      },
      {
        title: '异常信息',
        width: '200px',
        className: 'text-left',
        render: 'billComplianceVOS'
      },
      { title: '托运人', index: 'shipperName', width: '200px', className: 'text-left' },
      { title: '网络货运人', index: 'enterpriseInfoName', width: '250px', className: 'text-left' },
      {
        title: '运费明细',
        className: 'text-right',
        width: '200px',
        render: 'freightDetails'
      },
      {
        title: '服务类型',
        className: 'text-left',
        width: '100px',
        index: 'serviceTypeLabel'
      },
      {
        title: '装货地',
        className: 'text-left',
        width: '250px',
        index: 'loadingPlace'
      },
      {
        title: '卸货地',
        className: 'text-left',
        width: '250px',
        index: 'dischargePlace'
      },
      {
        title: '货物信息',
        className: 'text-left',
        width: '250px',
        render: 'goodsInfoVOList'
      },
      {
        title: '承运司机',
        className: 'text-left',
        width: '200px',
        render: 'driverName'
      },
      {
        title: '车队长',
        className: 'text-left',
        width: '200px',
        render: 'payeeName'
      },
      {
        title: '运输信息',
        className: 'text-left',
        width: '280px',
        render: 'timeer'
      },
      {
        title: '操作',
        fixed: 'right',
        width: '90px',
        className: 'text-center block-td',
        buttons: [
          {
            text: '审核',
            click: _record => this.audit(_record),
            iif: item => item.representationsStatus == '2',
            acl: { ability: ['ORDER-RISK-audit'] }
          },
        
          {
            text: '详情',
            click: _record => this.viewEvaluate(_record),
            iif: item => item.representationsStatus !== '1',
            acl: { ability: ['ORDER-RISK-riskDetail'] }
          }
        ]
      }
    ];
  }
  initSTAudit(value: number) {
    if (value == 1) {
      this.schemaView = {
        properties: {
          billCode: {
            title: '订单号',
            type: 'string',
            default: this.auditId,
            ui: {
              widget: 'text'
            }
          },
          id: {
            title: '',
            type: 'string',
            default: this.auditIdR,
            ui: {
              hidden: true
            }
          },
          representationsCause: {
            title: '备注',
            type: 'string',
            maxLength: 50,
            ui: {
              placeholder: '通过可以不用填写原因 ，拒绝必须说明原因',
              widget: 'textarea',
              autosize: { minRows: 3, maxRows: 6 }
            }
          }
        }
      };
    } else {
      this.schemaView = {
        properties: {
          billCode: {
            title: '',
            type: 'string',
            default: `已选${this.selectedRows?.length}条订单`,
            ui: {
              widget: 'text'
            }
          },
          representationsCause: {
            title: '备注',
            type: 'string',
            maxLength: 50,
            ui: {
              placeholder: '通过可以不用填写原因 ，拒绝必须说明原因',
              widget: 'textarea',
              autosize: { minRows: 3, maxRows: 6 }
            }
          }
        }
      };
    }

    this.uiView = { '*': { spanLabelFixed: 110, grid: { span: 24 } } };
  }

  tabChange(item: any) {
    console.log(item);
  }

  selectChange(e: number) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  /**
   * 导入货源
   */
  importGoodsSource() {}

  /*
   * 审核关闭弹窗
   */
  handleCancel() {
    this.isVisibleRE = false;
  }
  /**
   * 审核通过按钮
   */
  handleOK() {
    let idList: any[] = [];
    if (this.selectedRows.length > 0) {
      this.selectedRows.forEach(item => {
        idList.push(item.id);
      });
    } else {
      idList.push(this.sfView.value.id);
    }
    const parms = {
      ids: idList,
      auditRemark: this.sfView.value.representationsCause,
      representationsStatus: 3,
      auditStatus: 2
    };
    this.service.request(this.service.$api_get_listRisk_audit, parms).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('审核通过成功！');
        this.isVisibleRE = false;
        this.st?.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  /**
   * 审核拒绝按钮
   */
  reject() {
    let idList: any[] = [];
    if (this.selectedRows.length > 0) {
      this.selectedRows.forEach(item => {
        idList.push(item.id);
      });
    } else {
      idList.push(this.sfView.value.id);
    }
    if (!this.sfView.value.representationsCause) {
      this.service.msgSrv.error('拒绝原因为空！');
      return;
    }
    const parms = {
      ids: idList,
      auditRemark: this.sfView.value.representationsCause,
      representationsStatus: 4,
      auditStatus: 3
    };
    this.service.request(this.service.$api_get_listRisk_audit, parms).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('审核拒绝成功！');
        this.isVisibleRE = false;
        this.st?.load(1);
        this.getGoodsSourceStatistical();
      }
    });
  }
  /**
   *审核
   */
  audit(item?: any) {
    if (item) {
      this.auditId = item.billCode;
      this.auditIdR = item.id;
      this.initSTAudit(1);
      this.isVisibleRE = true;
    } else {
      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('请选择订单！');
        return;
      } else {
        this.initSTAudit(2);
        this.isVisibleRE = true;
      }
    }
  }
  /**
   *查看详情
   */
  viewEvaluate(item: any) {
    this.router.navigate(['/order-management/risk-detail', item.id]);
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.reqParams, pageSize: -1 }, this.service.$api_get_asyncExportRiskBillList);
  }

}
